#!/usr/bin/env python
# -*- coding: utf-8 -*-
#come from:http://bbs.chinaunix.net/thread-3673280-1-1.html

from itertools import groupby
from pprint import PrettyPrinter,pprint

def keyfunc(e):
    return str(e['goid']), e['date']

def main():
    lt1 = [ 
            {'goid':1111,'kid':222222,'cost':2,'date':'2012-02-11'},
            {'goid':1112,'kid':222225,'cost':5,'date':'2012-05-11'},
            {'goid':1111,'kid':222226,'cost':8,'date':'2012-02-11'},
    ]
    
    pprint(lt1)
    print '='*50

    lt1 = sorted(lt1, key=keyfunc)
    pprint(lt1)
    print '='*50

    for k,g in groupby(lt1,keyfunc):
        print k,g
        for i in g:
            print '\t',i
    print '='*50
    
    data = {}
    for k, g in groupby(lt1, keyfunc):
        k1, k2 = k 
        if k1 not in data:
            data[k1] = {}

        data[k1][k2] = list(g)

    lt2 = [data]
    pp = PrettyPrinter()
    pp.pprint(lt2)


if __name__ == '__main__':
    main()
    